//
var agentCode = agent.agentCode;
var agentId = agent.id;
var uniStorage = chat_source == 'web' ? sessionStorage : localStorage
var sessionId = getSessionId(agentCode, uniStorage);
var aiConfigStr = agent.aiConfig || '';

//
function clearChatHistoryOne() {
    if (confirm('确定清空本聊天记录？')) {
        var chatHistoryObj = JSON.parse(localStorage.getItem('_chatHistoryObj') || '{}')
        if (chatHistoryObj instanceof Object) {
            delete chatHistoryObj[agentCode]
            localStorage.setItem('_chatHistoryObj', JSON.stringify(chatHistoryObj))
            location.reload()
        } else {
            localStorage.removeItem('_chatHistoryObj')
        }
    }
}


//
var vue = new Vue({
    el: '#chat_app',
    data: {
        upConf: {},
        chatList: [
            {
                id: '', // 消息id
                role: 'bot', // bot user
                type: 'text', // text pic
                content: agent.welcomeMsg || `我是您的AI助手，请问有什么能帮您？`, // 消息内容
            },
        ],
        fileUrl: '',
        fileList: [],
        userInputMsg: '',
        analyzeObj: {},
        contentObj: {},
        outputMsg: '',
        aiConfig:{},
        // 开场问题相关
        openingQuestions: [],
        showOpeningQuestions: false,

    },
    created: function () {
        // 初始化时双向绑定
        this.aiConfig = this.parseAiConfig(aiConfigStr);
        this.getUpConf()
        // 初始化开场问题
        this.initOpeningQuestions();
        
        // 处理欢迎语中的链接
        if (this.chatList.length > 0 && this.chatList[0].role === 'bot') {
            this.chatList[0].content = this.processWelcomeMessage(this.chatList[0].content);
            // 确保欢迎语有唯一的ID，避免被contentObj处理影响
            if (!this.chatList[0].id) {
                this.chatList[0].id = 'welcome_msg_' + Date.now();
            }
        }
        
        try {
            var chatHistoryObj = JSON.parse(localStorage.getItem('_chatHistoryObj') || '{}')
            // console.log('chatHistoryObj->', chatHistoryObj)
            if (chatHistoryObj instanceof Object) {
                var chatHistoryOne = chatHistoryObj[agentCode] || {}
                if (chatHistoryOne.chatList instanceof Array && chatHistoryOne.chatList.length > 0) {
                    this.chatList = chatHistoryOne.chatList || []
                    this.contentObj = chatHistoryOne.contentObj || {}
                    // 如果有历史记录，不显示开场问题
                    this.showOpeningQuestions = false;
                    // 对历史记录中的第一条机器人消息也进行链接处理
                    if (this.chatList.length > 0 && this.chatList[0].role === 'bot') {
                        this.chatList[0].content = this.processWelcomeMessage(this.chatList[0].content);
                        // 确保欢迎语有唯一的ID，避免被contentObj处理影响
                        if (!this.chatList[0].id) {
                            this.chatList[0].id = 'welcome_msg_' + Date.now();
                        }
                    }
                } else {
                    // 如果没有历史记录，显示开场问题
                    this.showOpeningQuestions = this.openingQuestions.length > 0;
                }
            } else {
                localStorage.removeItem('_chatHistoryObj')
                this.showOpeningQuestions = this.openingQuestions.length > 0;
            }
        } catch (e) {
            this.showOpeningQuestions = this.openingQuestions.length > 0;
        }
    },
    mounted: function () {
        // 初始加载时滚动到底部
        this.scrollToBottom();
        // 测试Markdown库是否正确加载
        this.testMarkdownLibraries();
    },
    watch: {
        // 监听消息列表变化，自动滚动
        chatList() {
            this.$nextTick(function () {
                this.scrollToBottom();
            }.bind(this));
        }
    },
    methods: {
        // 初始化开场问题
        initOpeningQuestions: function() {
            try {
                if (typeof agent !== 'undefined' && agent.openingQuestionsEnabled && agent.openingQuestions) {
                    var questions = typeof agent.openingQuestions === 'string' 
                        ? JSON.parse(agent.openingQuestions) 
                        : agent.openingQuestions;
                    this.openingQuestions = questions.filter(function(q) {
                        return q && q.trim() !== '';
                    });
                } else {
                    this.openingQuestions = [];
                }
            } catch (e) {
                console.error('Failed to parse opening questions:', e);
                this.openingQuestions = [];
            }
        },
        
        // 点击开场问题
        clickOpeningQuestion: function(question) {
            this.userInputMsg = question;
            this.sendTextMsg();
            this.showOpeningQuestions = false;
        },
        
        // 更新开场问题（从配置页面调用）
        updateOpeningQuestions: function() {
            this.initOpeningQuestions();
            // 如果当前没有对话历史，显示开场问题
            if (this.chatList.length <= 1) {
                this.showOpeningQuestions = this.openingQuestions.length > 0;
            }
        },
        
        // 更新欢迎语（从配置页面调用）
        updateWelcomeMessage: function(newWelcomeMsg) {
            if (this.chatList.length > 0 && this.chatList[0].role === 'bot') {
                var welcomeMsg = newWelcomeMsg || '我是您的AI助手，请问有什么能帮您？';
                // 处理欢迎语中的链接
                this.chatList[0].content = this.processWelcomeMessage(welcomeMsg);
                // 确保欢迎语有唯一的ID，避免被contentObj处理影响
                if (!this.chatList[0].id) {
                    this.chatList[0].id = 'welcome_msg_' + Date.now();
                }
                // 强制重新渲染
                this.$forceUpdate();
                this.setChatHistory(); // 保存到本地存储
            }
        },
        
        setChatHistory: function () {
            var chatHistoryObj = JSON.parse(localStorage.getItem('_chatHistoryObj') || '{}')
            if (chatHistoryObj instanceof Object) {
                chatHistoryObj[agentCode] = {
                    chatList: this.chatList || [],
                    contentObj: this.contentObj || {},
                }
                localStorage.setItem('_chatHistoryObj', JSON.stringify(chatHistoryObj))
            } else {
                localStorage.removeItem('_chatHistoryObj')
            }
        },
        getUpConf: function () {
            var f = {
                prefix: 'agent/' + agentCode + '/' + dayjs().format('YYYY-MM-DD'),
            }
            api_file_getUploadCredentials(f, function (res) {
                if (res.code == 200) {
                    this.upConf = res.data || {}
                }
            }.bind(this))
        },
        scrollToBottom() {
            const container = this.$refs.messageList;
            container.scrollTop = container.scrollHeight;
        },
        getMsgId: function () {
            return msgId = 'temp_' + Date.now() + '_' + Math.floor(1000 + Math.random() * 9000).toString();
        },
        addNewMsg: function (obj) {
            switch (obj.type) {
                case 'text':
                case 'pic':
                    var content = obj.content;
                    // 如果是文本消息，进行Markdown检测和处理
                    if (obj.type === 'text') {
                        var isMarkdown = this.isMarkdownContent(content);
                        console.log('User message - Is Markdown:', isMarkdown, 'Content:', content.substring(0, 50) + '...'); // 调试日志
                        
                        if (isMarkdown && typeof window.marked !== 'undefined' && typeof window.DOMPurify !== 'undefined') {
                            // 对用户的Markdown消息进行渲染
                            var contentWithLinks = this.processLinksInMessage(content, false);
                            content = DOMPurify.sanitize(marked.parse(contentWithLinks), {
                                ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'code', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'blockquote', 'a', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'del', 'hr', 'img'],
                                ALLOWED_ATTR: ['href', 'target', 'rel', 'class', 'title', 'src', 'alt', 'width', 'height'],
                                ALLOW_DATA_ATTR: false
                            });
                        } else {
                            // 非Markdown内容，只进行链接处理和基本的HTML转义
                            var escapedContent = content
                                .replace(/&/g, '&amp;')
                                .replace(/</g, '&lt;')
                                .replace(/>/g, '&gt;')
                                .replace(/"/g, '&quot;')
                                .replace(/'/g, '&#x27;')
                                .replace(/\n/g, '<br>');
                            content = this.processLinksInMessage(escapedContent, false);
                        }
                    }
                    this.chatList.push({
                        id: obj.id || '',
                        role: obj.role || 'user',
                        type: obj.type,
                        content: content,
                    })
                    break;
                case '--':
                    //
                    break;
            }
            this.$nextTick(function () {
                this.scrollToBottom();
            }.bind(this));
            if (obj.type == 'text') {
                this.setChatHistory()
            }
        },
        updChatList: function () {
            var list = this.chatList || []
            for (var i = 0; i < list.length; i++) {
                var el = list[i]
                var content = this.contentObj[el.id] || ''
                if (content) {
                    el.content = content
                    delete this.contentObj[el.id]
                }
            }
            this.setChatHistory()
        },
        // 检测内容是否为Markdown格式
        isMarkdownContent: function(content) {
            if (!content || typeof content !== 'string') return false;
            
            // Markdown特征检测
            var markdownPatterns = [
                /^#{1,6}\s+.+$/m,           // 标题 # ## ###
                /\*\*[^*]+\*\*/,            // 粗体 **text**
                /\*[^*]+\*/,                // 斜体 *text*
                /`[^`]+`/,                  // 行内代码 `code`
                /```[\s\S]*?```/,           // 代码块 ```code```
                /^\s*[-*+]\s+.+$/m,        // 无序列表 - * +
                /^\s*\d+\.\s+.+$/m,        // 有序列表 1. 2.
                /^\s*>\s+.+$/m,            // 引用 >
                /\[([^\]]+)\]\(([^)]+)\)/,  // 链接 [text](url)
                /!\[([^\]]*)\]\(([^)]+)\)/, // 图片 ![alt](url)
                /^\s*\|.+\|.*$/m,          // 表格 |col1|col2|
                /^---+$/m,                  // 分隔线 ---
                /~~[^~]+~~/                 // 删除线 ~~text~~
            ];
            
            // 计算匹配的模式数量
            var matchCount = 0;
            var matchedPatterns = [];
            for (var i = 0; i < markdownPatterns.length; i++) {
                if (markdownPatterns[i].test(content)) {
                    matchCount++;
                    matchedPatterns.push(i);
                }
            }
            
            // 降低检测阈值：只要有1个明显的markdown特征就认为是markdown
            if (matchCount >= 1) {
                // 检查是否有明显的markdown特征
                if (/```[\s\S]*?```/.test(content) ||     // 代码块
                    /^#{1,6}\s+.+$/m.test(content) ||     // 标题
                    /^\s*\|.+\|.*$/m.test(content) ||     // 表格
                    /\*\*[^*]+\*\*/.test(content) ||      // 粗体
                    /^\s*[-*+]\s+.+$/m.test(content) ||   // 列表
                    /^\s*\d+\.\s+.+$/m.test(content) ||   // 有序列表
                    /^\s*>\s+.+$/m.test(content)) {       // 引用
                    return true;
                }
            }
            
            // 如果有2个或以上的特征，也认为是markdown
            if (matchCount >= 2) {
                return true;
            }
            
            return false;
        },

        // 测试库是否加载
        testMarkdownLibraries: function() {
            console.log('Testing Markdown libraries...');
            console.log('marked available:', typeof window.marked !== 'undefined');
            console.log('DOMPurify available:', typeof window.DOMPurify !== 'undefined');
            if (typeof window.marked !== 'undefined') {
                var testMd = '# Test\n**Bold text**';
                var result = marked.parse(testMd);
                console.log('marked test result:', result);
            }
            
            // 暴露测试函数到window对象上，方便调试
            var self = this;
            window.testMarkdown = function(content) {
                console.log('Testing content:', content);
                console.log('Is Markdown:', self.isMarkdownContent(content));
                if (typeof window.marked !== 'undefined') {
                    var result = marked.parse(content);
                    console.log('Rendered result:', result);
                    return result;
                }
                return 'Marked library not available';
            };
            
            // 暴露重新处理所有消息的函数
            window.reprocessAllMessages = function() {
                console.log('Reprocessing all messages...');
                for (var i = 0; i < self.chatList.length; i++) {
                    var message = self.chatList[i];
                    if (message.type === 'text') {
                        var originalContent = message.content;
                        // 先重置内容为原始状态（假设它可能已经被处理过）
                        
                        var isMarkdown = self.isMarkdownContent(originalContent);
                        console.log('Message', i, 'Is Markdown:', isMarkdown);
                        
                        if (isMarkdown && typeof window.marked !== 'undefined' && typeof window.DOMPurify !== 'undefined') {
                            var contentWithLinks = self.processLinksInMessage(originalContent, false);
                            var processedContent = DOMPurify.sanitize(marked.parse(contentWithLinks), {
                                ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'code', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'blockquote', 'a', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'del', 'hr', 'img'],
                                ALLOWED_ATTR: ['href', 'target', 'rel', 'class', 'title', 'src', 'alt', 'width', 'height'],
                                ALLOW_DATA_ATTR: false
                            });
                            message.content = processedContent;
                        }
                    }
                }
                self.$forceUpdate();
                console.log('All messages reprocessed');
            };
        },

        updTempMsg: function (obj) {
            // console.log('obj->', obj)
            this.$set(this.analyzeObj, obj.msgId, false);
            
            var processedContent;
            
            // 检测是否为Markdown内容
            var isMarkdown = this.isMarkdownContent(obj.content);
            console.log('Content:', obj.content.substring(0, 100) + '...'); // 调试日志
            console.log('Is Markdown:', isMarkdown); // 调试日志
            
            if (isMarkdown) {
                // 检查是否有marked和DOMPurify库
                if (typeof window.marked !== 'undefined' && typeof window.DOMPurify !== 'undefined') {
                    // 先处理链接，再进行Markdown解析和安全过滤
                    var contentWithLinks = this.processLinksInMessage(obj.content, false);
                    processedContent = DOMPurify.sanitize(marked.parse(contentWithLinks), {
                        ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'code', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'blockquote', 'a', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'del', 'hr', 'img'],
                        ALLOWED_ATTR: ['href', 'target', 'rel', 'class', 'title', 'src', 'alt', 'width', 'height'],
                        ALLOW_DATA_ATTR: false
                    });
                    console.log('Markdown rendered:', processedContent.substring(0, 100) + '...'); // 调试日志
                } else {
                    console.warn('Markdown libraries not available, falling back to plain text'); // 调试日志
                    // 降级处理：只处理链接和基本的HTML转义
                    var escapedContent = obj.content
                        .replace(/&/g, '&amp;')
                        .replace(/</g, '&lt;')
                        .replace(/>/g, '&gt;')
                        .replace(/"/g, '&quot;')
                        .replace(/'/g, '&#x27;')
                        .replace(/\n/g, '<br>');
                    processedContent = this.processLinksInMessage(escapedContent, false);
                }
            } else {
                // 非Markdown内容，只进行链接处理和基本的HTML转义
                var escapedContent = obj.content
                    .replace(/&/g, '&amp;')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;')
                    .replace(/"/g, '&quot;')
                    .replace(/'/g, '&#x27;')
                    .replace(/\n/g, '<br>'); // 保留换行
                    
                processedContent = this.processLinksInMessage(escapedContent, false);
            }
            
            this.$set(this.contentObj, obj.msgId, processedContent);
            this.$forceUpdate();
            this.$nextTick(function () {
                this.scrollToBottom();
            }.bind(this));
            if (obj.tag == 'STOP') {
                this.updChatList()
            } else {
                this.setChatHistory()
            }
        },
        
        // 强制渲染Markdown（用于测试）
        forceRenderMarkdown: function(content) {
            if (typeof window.marked !== 'undefined' && typeof window.DOMPurify !== 'undefined') {
                try {
                    var result = DOMPurify.sanitize(marked.parse(content), {
                        ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'code', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'blockquote', 'a', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'del', 'hr', 'img'],
                        ALLOWED_ATTR: ['href', 'target', 'rel', 'class', 'title', 'src', 'alt', 'width', 'height'],
                        ALLOW_DATA_ATTR: false
                    });
                    console.log('Force rendered:', result);
                    return result;
                } catch (e) {
                    console.error('Markdown rendering error:', e);
                    return content;
                }
            } else {
                console.warn('Markdown libraries not available');
                return content;
            }
        },
        
        handleEnter: function (event) {
            // 阻止默认行为（避免换行）
            event.preventDefault();
            this.sendTextMsg()
        },
        setAnalyze: function (obj) {
            var msgId = this.getMsgId()
            var content = obj.content || '分析中'
            this.addNewMsg({
                content: content,
                type: 'text',
                role: 'bot',
                id: msgId
            })
            this.$set(this.analyzeObj, msgId, true);
            this.$set(this.contentObj, msgId, content);
            return msgId
        },
        sendTextMsg: function () {
            var userInputMsg = (this.userInputMsg || '').trim();
            if (!userInputMsg) return this.$message.warning('请输入信息！');
            this.addNewMsg({
                content: userInputMsg,
                type: 'text'
            })
            this.userInputMsg = ''
            var msgId = this.setAnalyze({content: '分析中'})
            //
            this.sendChatMsg({text: userInputMsg, msgId: msgId})
        },
        sendChatMsg: async function (obj) {
            //
            var stream = true
            var content = []
            if (obj.text) content.push({type: 'text', text: obj.text,})
            if (obj.fileUrl) content.push({type: 'image_url', image_url: obj.fileUrl,})


            var f = {
                agentCode: agentCode,
                agentId: agentId,
                messages: [
                    {content: JSON.stringify(content), role: 'user',}
                ],
                stream: stream,
                sessionId: sessionId,
                source: chat_source
            }
            var contents = ''
            api_chat_stream_send(f, function (chunk) {
                var finishReason = chunk.finishReason || ''
                var content = chunk.content || ''
                // console.log('chunk->', chunk)
                contents += content || ''
                // console.log('contents->', contents)
                this.updTempMsg({content: contents, type: 'text', role: 'bot', msgId: obj.msgId, tag: finishReason,})
            }.bind(this))
        },
        sendFileMsg: function () {
            var msgId = this.setAnalyze({content: '图片分析中'})
            var fileUrl = this.fileUrl || ''
            this.sendChatMsg({fileUrl: fileUrl, msgId: msgId})
        },
        getFileKey: function (file, dir) {
            var fileType = (file.name || '').split('.').pop() || 'jpeg'
            var filename = Date.now() + '_' + parseInt(Math.random() * 1000) + '.' + fileType
            var filekey = dir + '/' + filename
            return filekey
        },
        upLoadFile: function (obj) {
            var conf = this.upConf || {}
            var filekey = this.getFileKey(obj.file, conf.dir)
            // 创建 FormData 对象，用于上传文件
            const formData = new FormData();
            formData.append('key', filekey);
            formData.append('OSSAccessKeyId', conf.ossAccessKeyId);
            formData.append('policy', conf.policy);
            formData.append('signature', conf.signature);
            formData.append('file', obj.file);
            formData.append("success_action_status", 200);
            formData.append('host', conf.host)
            //
            api_oss_upload_file(formData, function (percent) {
                console.log('percent->', percent)
            }.bind(this), function (res) {
                var fileUrl = conf.host + '/' + filekey
                console.log('fileUrl->', fileUrl)
                this.fileUrl = fileUrl
                if (obj.msgId) {
                    this.$set(this.contentObj, obj.msgId, fileUrl);
                    this.$forceUpdate();
                    this.updChatList()
                }
                // this.fileList.push(fileUrl)
                this.sendFileMsg()
            }.bind(this))
        },
        fileChange: function (e) {
            const file = e.target.files[0];
            if (file && file.type.match('image.*')) {
                var reader = new FileReader();
                reader.onload = function (event) {
                    // 使用 event.target.result 获取文件内容
                    var result = event.target.result;
                    //
                    this.addNewMsg({content: result, type: 'pic', id: this.getMsgId()})
                    //
                    this.upLoadFile({file: file, msgId: msgId})
                }.bind(this);
                reader.readAsDataURL(file);
                e.target.value = ''; // 清空文件输入
            }
        },
        handleImageLoad(event) {
            // console.log('图片加载成功', event.target);
            // // 可以在这里执行图片加载后的操作，如获取尺寸
            // const { width, height } = event.target;
            // console.log('图片宽高:', width, height);
            //
            this.scrollToBottom()
        },
        handleImageError(error) {
            // console.error('图片加载失败', error);
            //
            this.scrollToBottom()
        },
        // 数据解析方法
        parseAiConfig(config) {
            try {
                return typeof config === 'string' ? JSON.parse(config) : config;
            } catch {
                return {};
            }
        },
        
        // 通用的链接处理方法（用于所有消息内容）
        processLinksInMessage: function(message, isWelcomeMessage) {
            if (!message) return message;
            
            // 更强健的URL正则表达式，支持各种常见的URL格式
            var urlRegex = /((?:https?:\/\/)?(?:www\.)?[a-zA-Z0-9][-a-zA-Z0-9]*[a-zA-Z0-9]*\.)+[a-zA-Z]{2,}(?::\d+)?(?:\/[^\s<>"{}|\\^`\[\]]*)?/gi;
            
            // 调试日志
            if (window.location.search.includes('debug')) {
                console.log('Processing links in message:', message, 'isWelcome:', isWelcomeMessage);
            }
            
            // 替换链接为HTML链接，添加特殊样式和属性
            var processedMessage = message.replace(urlRegex, function(url) {
                // 标准化URL - 如果没有协议则添加https
                var normalizedUrl = url;
                if (!url.match(/^https?:\/\//i)) {
                    normalizedUrl = 'https://' + url;
                }
                
                // 基本的URL格式验证
                try {
                    new URL(normalizedUrl);
                } catch (e) {
                    return url; // 如果URL格式无效，返回原文本
                }
                
                // 对URL进行基本的安全检查，转义特殊字符
                var hrefUrl = normalizedUrl.replace(/"/g, '&quot;').replace(/'/g, '&#x27;');
                
                // 截断显示过长的URL
                var displayUrl = url.length > 50 ? url.substring(0, 47) + '...' : url;
                // 对显示的URL进行HTML转义
                var safeDisplayUrl = displayUrl.replace(/[<>&"']/g, function(match) {
                    var escapeMap = {
                        '<': '&lt;',
                        '>': '&gt;',
                        '&': '&amp;',
                        '"': '&quot;',
                        "'": '&#x27;'
                    };
                    return escapeMap[match];
                });
                
                // 对title属性中的URL也进行转义
                var titleUrl = normalizedUrl.replace(/"/g, '&quot;').replace(/'/g, '&#x27;');
                
                // 根据消息类型选择不同的CSS类
                var linkClass = isWelcomeMessage ? 'welcome-msg-link' : 'chat-msg-link';
                
                var linkHtml = '<a href="' + hrefUrl + '" target="_blank" rel="noopener noreferrer" class="' + linkClass + '" title="点击打开链接: ' + titleUrl + '">' + safeDisplayUrl + '</a>';
                
                // 调试日志
                if (window.location.search.includes('debug')) {
                    console.log('Created link:', url, '->', linkHtml);
                }
                
                return linkHtml;
            });
            
            // 调试日志
            if (window.location.search.includes('debug')) {
                console.log('Processed message result:', processedMessage);
            }
            
            return processedMessage;
        },
        
        // 处理欢迎语中的链接（保持向后兼容）
        processWelcomeMessage: function(message) {
            return this.processLinksInMessage(message, true);
        },
    }
})